<?php
class Server {
  public static function get_objs($orm, $sys, $inst, $is_iframe) {
    $req = json_decode(Utils::get_param('req', '[]'));
    $categories = $orm->get('pb_ecom_category', NULL, NULL, NULL, NULL, NULL)->d;
    
    $root = new stdClass();
    $root->id = 0;
    $root->name = 'ROOT';
    $root->parent_id = -1;
    Server::__create_root($categories, $root);
    
    $rslt = new stdClass();
    $rslt->data = array();
    Server::__get_all($root, $req->cat, $rslt, false);
    
    
    $opts = new stdClass(); 
    $opts->cd = 't.status= 1 AND name LIKE :v0';
    $opts->cdv = array(':v0' => '%' . $req->search . '%');
    if ($req->cat != 0) {
      $opts->cd .= ' AND (';
      foreach ($rslt->data as $idx => &$itm) {
        $opts->cd .= "t.category_id = :v" . ($idx + 1);
        $opts->cdv[":v" . ($idx + 1)] = "$itm";
        if ($idx < count($rslt->data)  -1) {
          $opts->cd .= ' OR ';
        }
      }
      $opts->cd .= ')';
    }
    
    $opts->sel = 't.id, t.track_id, t.name, t.price, t.curr, t.brief, t.enabled_member, t.sold__';
    $data = $orm->get('pb_ecom_product', NULL, NULL, $req->pg, CAT_PNUM, $opts);
    foreach ($data->d as $itm) {
      $itm->__img = PLGN_DIR . basename(dirname(__FILE__)) . '/no_image.gif';
      $opts = new stdClass(); 
      $opts->cd = 't.product_track_id = :v1 AND t.is_default = :v2';
      $opts->cdv = array(':v1' => $itm->track_id, ':v2' => 1);
      $rslt = $orm->get('pb_ecom_product_img', NULL, NULL, NULL, NULL, $opts)->d;
      if (count($rslt) > 0) {
        $itm->__img = $rslt[0]->file;
      }
    }
    
    echo json_encode($data);
  }
  
  public static function __get_all($node, $id, $rslt, $is_to_add) {
    if ($node->id == $id || $is_to_add) {
      $rslt->data[] = $node->id;
    }
    foreach ($node->__c as &$itm) {
      Server::__get_all($itm, $id, $rslt, $is_to_add || $node->id == $id);
    }
  }
  
  public static function __create_root($arr, $node) {
    for ($i = 0, $il = count($arr); $i < $il; $i++) {
      $itm = $arr[$i];
      if ($itm->parent_id == $node->id) {
        $itm->__c = array();
        $node->__c[] = $itm;
        Server::__create_root($arr, $itm);
      }
    }
  }
}
?>